package com.example.myapplication;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.app.AlertDialog;
import android.content.DialogInterface;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

public class MainActivity extends AppCompatActivity {
    TextView blog_title_1;
    TextView blog_title_2;
    ImageView back_button;
    TextView usernameView;
    ImageButton menu_button;
    CardView dropdown_menu;
    boolean isMenuShowing = false;
    BroadcastReceiver blogReceiver;
    TextView blogCountView; // 显示博客数量的TextView
    private long lastUpdateTime;
    private LinearLayout blogsContainer;
    private List<Blog> blogsList = new ArrayList<>();

    @Override
    protected void onStart() {
        super.onStart();
        if(blogReceiver == null) {
            blogReceiver = new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    // 防重检查（500ms内不重复处理）
                    if(System.currentTimeMillis() - lastUpdateTime < 500) return;

                    try {
                        String countStr = blogCountView.getText().toString();
                        if(!TextUtils.isEmpty(countStr)) {
                            int currentCount = Integer.parseInt(countStr);
                            blogCountView.setText(String.valueOf(currentCount + 1));
                            lastUpdateTime = System.currentTimeMillis();
                        }
                    } catch (NumberFormatException e) {
                        Log.e("Blog", "Invalid count format", e);
                    }
                }
            };
        }
        LocalBroadcastManager.getInstance(this)
                .registerReceiver(blogReceiver, new IntentFilter("blog_num"));
    }

    @Override
    protected void onDestroy() {
            LocalBroadcastManager.getInstance(this).unregisterReceiver(blogReceiver);
        super.onDestroy();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        dropdown_menu = findViewById(R.id.dropdown_menu);
        usernameView = findViewById(R.id.username); // 确保布局中有这个ID
        blogCountView = findViewById(R.id.blog_count);
        // 加载当前用户名
        loadCurrentUsername();
        blogsContainer = findViewById(R.id.blogs_container);

        blog_title_1 = findViewById(R.id.blog_title_1);//查看博客1
        blog_title_1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent it = new Intent(MainActivity.this,Main2Activity.class);
                startActivity(it);
            }
        });
        blog_title_2 = findViewById(R.id.blog_title_2);//查看博客2
        blog_title_2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent it = new Intent(MainActivity.this,Main3Activity.class);
                startActivity(it);
            }
        });
        back_button = findViewById(R.id.back_button);
        back_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new AlertDialog.Builder(MainActivity.this)
                        .setTitle("提示")
                        .setMessage("确定要退出登录吗？")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Intent it = new Intent(MainActivity.this, LoginActivity.class);
                                startActivity(it);
                            }
                        })
                        .setNegativeButton("取消", null)
                        .show();
            }
        });
        menu_button = findViewById(R.id.menu_button);
        menu_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                toggleDropdownMenu();
            }
        });
        setupMenuItems();
    }



    private void addBlogCard(Blog blog) {
        CardView blogCard = (CardView) getLayoutInflater().inflate(R.layout.blog_item, null);

        ImageView coverImage = blogCard.findViewById(R.id.blog_cover);
        TextView titleView = blogCard.findViewById(R.id.blog_title);
        TextView summaryView = blogCard.findViewById(R.id.blog_summary);
        TextView dateView = blogCard.findViewById(R.id.blog_date);

        titleView.setText(blog.getTitle());
        summaryView.setText(blog.getContent().length() > 50 ?
                blog.getContent().substring(0, 50) + "..." :
                blog.getContent());

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
        dateView.setText(sdf.format(new Date(blog.getTimestamp())));

        // 添加到容器顶部
        blogsContainer.addView(blogCard, 0);
        updateBlogCount();
    }

    private void updateBlogCount() {
        blogCountView.setText(String.valueOf(blogsList.size()));
    }

    private void toggleDropdownMenu() {
        if (isMenuShowing) {
            hideDropdownMenu();
        } else {
            showDropdownMenu();
        }
    }

    private void showDropdownMenu() {
        dropdown_menu.setVisibility(View.VISIBLE);
        isMenuShowing = true;
    }

    private void hideDropdownMenu() {
        dropdown_menu.setVisibility(View.GONE);
        isMenuShowing = false;
    }

    private void setupMenuItems() {
        // 修改基本信息
        findViewById(R.id.menu_edit_profile).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                hideDropdownMenu();
                Intent intent = new Intent(MainActivity.this, EditProfileActivity.class);
                startActivityForResult(intent, 1); // 使用requestCode=1
            }
        });

        // 发布博客
        findViewById(R.id.menu_post_blog).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                hideDropdownMenu();
                Intent intent = new Intent(MainActivity.this, PostBlogActivity.class);
                startActivityForResult(intent,2);
            }
        });

        // 修改密码
        findViewById(R.id.menu_change_password).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                hideDropdownMenu();
                Intent intent = new Intent(MainActivity.this, ChangePasswordActivity.class);
                startActivity(intent);
            }
        });
    }

    @Override
    public void onBackPressed() {
        if (isMenuShowing) {
            hideDropdownMenu();
        } else {
            super.onBackPressed();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        // 当Activity失去焦点时隐藏菜单
        hideDropdownMenu();
    }
    private void loadCurrentUsername() {
        String currentUser = UserPrefs.getCurrentUsername(this);
        if (usernameView != null) {
            usernameView.setText(currentUser);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 2 && resultCode == RESULT_OK && data != null) {
            Blog newBlog = (Blog) data.getSerializableExtra("new_blog");
            if (newBlog != null) {
                blogsList.add(0, newBlog); // 添加到列表顶部
                addBlogCard(newBlog); // 添加卡片到UI
            }
        }
    }

}
